package com.sh.tcp;

import java.net.InetSocketAddress;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
* @comments
* @author  zg
* @date 2018年4月6日
*/
public class SmartServer {
	private Logger logger = LogManager.getLogger(this.getClass());
	
	private int port;

	public SmartServer(int port) {
		this.port = port;
	}

	public void start() throws Exception {
		final SmartServerHandler serverHandler = new SmartServerHandler();
		EventLoopGroup group = new NioEventLoopGroup();//使用 NioEventLoopGroup
		try {
			ServerBootstrap b = new ServerBootstrap();//创建ServerBootstrap
			b.group(group);
			b.channel(NioServerSocketChannel.class);//使用的 NIO的传输 Channel
			b.localAddress(new InetSocketAddress(port));
			b.childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				public void initChannel(SocketChannel ch) throws Exception {
					ChannelPipeline cp = ch.pipeline();
					cp.addLast(new LineBasedFrameDecoder(1024));//解决tcp沾包问题
					//cp.addLast(new StringDecoder());
					cp.addLast(serverHandler);//EchoServerHandler 被标注为@Shareable，所以我们可以总是使用同样的实例
				}
			});

			ChannelFuture f = b.bind().sync();//异步地绑定服务器
			logger.info("SmartServer在 {} 启动监听...",f.channel().localAddress());
			//f.channel().closeFuture().sync();//获取 Channel的CloseFuture，并且 阻 塞 当 前 线程直到它完成
		} finally {
			//logger.info("shutdownGracefully， 关闭 EventLoopGroup，释放资源 ");
			//group.shutdownGracefully().sync();//关闭 EventLoopGroup，释放所有资源（包括所有被创建的线程）
		}
	}
	
	public static void main(String[] args) throws Exception {
		new SmartServer(8001).start();
		
	}
	
}
